package com.five.taotao.guide;


import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.NumberPicker;
import android.widget.ScrollView;

import com.five.taotao.Adapter.HeaderAdapter;
import com.five.taotao.R;
import com.five.taotao.entity.Store;
import com.five.taotao.selfwidget.MyListView;
import com.five.taotao.social.SocialAdapter;
import com.five.taotao.util.ThreadPoolManager;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * A simple {@link Fragment} subclass.
 */
public class SocialFragment extends Fragment{


    @BindView(R.id.pull_lv)
    MyListView listView;

    @BindView(R.id.vp)
    ViewPager viewPager;


    private View v;
    private ArrayList<ImageView> arrayList;
    private int[] imageResId; // 图片ID
    private List<View> dots; // 图片标题正文的那些点
    private int num = 600;
    private HeaderAdapter adapter;
    private DisplayMetrics dm;//屏幕尺寸管理器
    //    private int visibleItemCount;//当前可视item的数量
    private int visibleLastIndex = 0;   //最后的可视项索引
    private List<Store> data;//品牌展示数据
    private SocialAdapter lvadapter;

    @BindView(R.id.shequ)
    PullToRefreshScrollView top1;
    ThreadPoolManager tm = ThreadPoolManager.getInstance();//线程池管理
    ScheduledExecutorService ses = tm.getScheduledExcutorService();


    public SocialFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (v == null) {
            v = inflater.inflate(R.layout.fragment_social, container, false);
            ButterKnife.bind(this, v);
            dm = new DisplayMetrics();
            getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
            //初始化数据
            imageResId = new int[]{R.drawable.img6, R.drawable.img7, R.drawable.img8
                    , R.drawable.img9, R.drawable.img10};
            initData();
            adapter = new HeaderAdapter(arrayList);
            viewPager.setAdapter(adapter);
            ViewGroup.LayoutParams vp_layoutParams = viewPager.getLayoutParams();
            vp_layoutParams.height = dm.widthPixels * 3 / 7;// 设置控件的高强
            viewPager.setLayoutParams(vp_layoutParams); //使设置好的布局参数应用到控件
            viewPager.setCurrentItem(num);
            ses.scheduleWithFixedDelay(mRunnable, 3000, 4000, TimeUnit.MILLISECONDS);

            // 设置一个监听器，当ViewPager中的页面改变时调用
            viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                private int oldPosition = 0;

                @Override
                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                }

                @Override
                public void onPageSelected(int position) {
                    num = position;
                    position = position % arrayList.size();
                    dots.get(oldPosition).setBackgroundResource(R.drawable.dot_normal);
                    dots.get(position).setBackgroundResource(R.drawable.dot_focused);

                    oldPosition = position;

                }

                @Override
                public void onPageScrollStateChanged(int state) {

                }
            });
            //listview
            data = new ArrayList<>();
            initData2();
            lvadapter = new SocialAdapter(data, getActivity());
            listView.setAdapter(lvadapter);
            top1.setMode(PullToRefreshBase.Mode.BOTH);
            top1.setScrollingWhileRefreshingEnabled(true);
            //scrollview的滚动监听
            top1.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ScrollView>() {
                @Override
                public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                    top1.onRefreshComplete();
                }

                @Override
                public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                    initData2();
                    top1.onRefreshComplete();
                    lvadapter.notifyDataSetChanged();

                }
            });



        }

        return v;
    }
    //listview

    /**
     * 初始化数据
     *
     * @return
     */
    private void initData2() {

        Store store = new Store();
        store.setImg1(R.drawable.psb);
        store.setImg2(R.drawable.img17);
        store.setTv1("雨铃铛");
        store.setTv2("编辑精选");
        store.setTv3("Hello,宝宝们，欢迎进入这家好店。");
        data.add(store);
        store = new Store();
        store.setImg1(R.drawable.psb);
        store.setImg2(R.drawable.img18);
        store.setTv1("楚楚娘");
        store.setTv2("编辑精选");
        store.setTv3("Hello,宝宝们，欢迎进入这家好店。");
        data.add(store);
        store = new Store();
        store.setImg1(R.drawable.psb);
        store.setImg2(R.drawable.img13);
        store.setTv1("VivianJQY");
        store.setTv2("编辑精选");
        store.setTv3("Hello,宝宝们，欢迎进入这家好店。");
        data.add(store);
//        store = new Store();
//        store.setImg1(R.drawable.psb);
//        store.setImg2(R.drawable.img12);
//        store.setTv1("小妹酱");
//        store.setTv2("编辑精选");
//        store.setTv3("Hello,宝宝们，欢迎进入这家好店。");
//        list.add(store);
//        store = new Store();
//        store.setImg1(R.drawable.psb);
//        store.setImg2(R.drawable.img15);
//        store.setTv1("楚楚娘");
//        store.setTv2("编辑精选");
//        store.setTv3("Hello,宝宝们，欢迎进入这家好店。");
//        list.add(store);
//        store = new Store();
//        store.setImg1(R.drawable.psb);
//        store.setImg2(R.drawable.img16);
//        store.setTv1("楚楚娘");
//        store.setTv2("编辑精选");
//        store.setTv3("Hello,宝宝们，欢迎进入这家好店。");
//        list.add(store);
//        store = new Store();
//        store.setImg1(R.drawable.psb);
//        store.setImg2(R.drawable.img11);
//        store.setTv1("楚楚娘");
//        store.setTv2("编辑精选");
//        store.setTv3("Hello,宝宝们，欢迎进入这家好店。");
//        list.add(store);
//        store = new Store();
//        store.setImg1(R.drawable.psb);
//        store.setImg2(R.drawable.img18);
//        store.setTv1("楚楚娘");
//        store.setTv2("编辑精选");
//        store.setTv3("Hello,宝宝们，欢迎进入这家好店。");
//        list.add(store);
//
    }

    private Runnable mRunnable = new Runnable() {
        public void run() {
            num++;//num 增加
            Message message = viewHandler.obtainMessage(1);
            message.arg1 = num;
            viewHandler.sendMessage(message);
        }

    };

    private final Handler viewHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                viewPager.setCurrentItem(msg.arg1);//ViewPager换到下一页。
            }
            super.handleMessage(msg);
        }

    };

    /**
     * 添加自动滚动广告数据
     */
    public void initData() {
        arrayList = new ArrayList<>();
        for (int i = 0; i < imageResId.length; i++) {
            ImageView imageView = new ImageView(getContext());
            imageView.setImageResource(imageResId[i]);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            arrayList.add(imageView);
        }
        dots = new ArrayList<>();
        // 初始化点图
        dots.add(v.findViewById(R.id.v_dot0));
        dots.add(v.findViewById(R.id.v_dot1));
        dots.add(v.findViewById(R.id.v_dot2));
        dots.add(v.findViewById(R.id.v_dot3));
        dots.add(v.findViewById(R.id.v_dot4));


    }


//    @Override
//    public void onScrollStateChanged(AbsListView view, int scrollState) {
//        //外层有Scrollview,有可能抵消了listview的滑动
//        int itemsLastIndex = adapter.getCount() - 1;    //数据集最后一项的索引
//        if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE && itemsLastIndex == visibleLastIndex) {
//            initData2();
//            lvadapter.notifyDataSetChanged();
//            Log.e("优化在这里", "草");
//
//        }
//    }
//
//    @Override
//    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
////        this.visibleItemCount = totalItemCount;
//        visibleLastIndex = firstVisibleItem + visibleItemCount - 1;
//        if (visibleLastIndex == totalItemCount) {
//            initData2();
//            lvadapter.notifyDataSetChanged();
//        }
//    }

}
